//
//  ST_PictureVideoProfileController.swift
//  btvideo
//
//  Created by mac on 2020/1/21.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import SwiftyAttributes
import SwiftyUserDefaults
import TZImagePickerController
import RealmSwift


fileprivate let previewBoxWidth = 150.cgFloat/375.0*ScreenWidth

class ST_RegisterAvatarController: UIViewController  {
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        //ST_BTGlobalDataCenter.shared.endLogPageView("UploadAvatar")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        super.viewWillAppear(animated)
        
        self.player?.play()
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //ST_BTGlobalDataCenter.shared.beginLogPageView("UploadAvatar")
        
        view.backgroundColor = Color.white
        
        view.addSubview(styleBtn)
        styleBtn.frame = CGRect.init(x: 150, y: 73-20+statusBarHeight, width: 153+10+70, height: 24)
        styleBtn.alpha = 0.1
        
        
        view.addSubview(content_label)
        content_label.frame = CGRect.init(x: ScreenWidth, y: styleBtn.frame.maxY + 1, width: ScreenWidth - 100, height: 30)
        
        view.addSubview(preview_box)
        preview_box.snp.makeConstraints { (make) in
            make.width.height.equalTo(previewBoxWidth)
            make.centerX.equalToSuperview()
            make.top.equalTo(content_label.snp.bottom).offset(69)
        }
        
        view.addSubview(preview_right_bottom_view)
        preview_right_bottom_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(51)
            make.right.equalTo(preview_box.snp.right).offset(6)
            make.bottom.equalTo(preview_box.snp.bottom).offset(6)
        }
        
        preview_box.addSubview(preview_center_view)
        preview_center_view.snp.makeConstraints { (make) in
            make.width.equalTo(34)
            make.height.equalTo(28)
            make.center.equalToSuperview()
        }
        
        
        preview_box.addSubview(preview_picutre_view)
        preview_picutre_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        
        preview_box.addSubview(avPlayerView)
        avPlayerView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        //        preview_box.addSubview(preview_layer_content_view)
        //        preview_layer_content_view.snp.makeConstraints { (make) in
        //            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: preview_box_border_width, left: preview_box_border_width, bottom: preview_box_border_width, right: preview_box_border_width))
        //        }
        //
        //        preview_box.addSubview(preview_icon_view)
        //        preview_icon_view.snp.makeConstraints { (make) in
        //            make.centerX.equalToSuperview()
        //            make.centerY.equalToSuperview().offset(-10)
        //            make.width.equalTo(104)
        //            make.height.equalTo(105)
        //        }
        //
        //        preview_box.addSubview(preview_btn_view)
        //        preview_btn_view.snp.makeConstraints { (make) in
        //            make.centerX.equalToSuperview()
        //            make.bottom.equalToSuperview().offset(-39)
        //            make.width.equalTo(40)
        //            make.height.equalTo(40)
        //        }
        
        self.view.addSubview(media_picker_click_btn)
        media_picker_click_btn.snp.makeConstraints { (make) in
            make.top.bottom.right.left.equalTo(preview_box)
        }
        
        
        
        view.addSubview(center_image_view)
        center_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(60)
            make.centerX.equalToSuperview()
            make.top.equalTo(preview_box.snp.bottom).offset(74)
        }
        
        view.addSubview(center_mistake_image_view)
        center_mistake_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(16)
            make.centerX.equalTo(center_image_view)
            make.bottom.equalTo(center_image_view.snp.top).offset(-5)
        }
        
        view.addSubview(left_image_view)
        left_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(center_image_view)
            make.right.equalTo(center_image_view.snp.left).offset(-30)
            make.top.equalTo(center_image_view)
        }
        
        view.addSubview(left_mistake_image_view)
        left_mistake_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(16)
            make.centerX.equalTo(left_image_view)
            make.bottom.equalTo(left_image_view.snp.top).offset(-5)
        }
        
        view.addSubview(right_image_view)
        right_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(center_image_view)
            make.left.equalTo(center_image_view.snp.right).offset(30)
            make.top.equalTo(center_image_view)
        }
        
        view.addSubview(right_mistake_image_view)
        right_mistake_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(16)
            make.centerX.equalTo(right_image_view)
            make.bottom.equalTo(right_image_view.snp.top).offset(-5)
        }
        
        
        view.addSubview(center_label)
        center_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(right_image_view.snp.bottom).offset(8)
        }
        
        view.addSubview(left_label)
        left_label.snp.makeConstraints { (make) in
            make.centerX.equalTo(left_image_view)
            make.top.equalTo(right_image_view.snp.bottom).offset(8)
        }
        
        view.addSubview(right_label)
        right_label.snp.makeConstraints { (make) in
            make.centerX.equalTo(right_image_view)
            make.top.equalTo(right_image_view.snp.bottom).offset(8)
        }
        
        view.addSubview(next_btn)
        next_btn.alpha = 0.1
        next_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(45)
            make.top.equalTo(right_label.snp.bottom).offset(50)
            make.right.equalToSuperview().offset(-40)
        }
        
        //TianRegisterStepManager.shared.addHelperBtn(root_view: view)
        
        
        guard let user = ST_RegisterMonitor.shared.regist_response_account()?.userinfo else {
            return
        }
        
        
       
        if  user.avatar.count > 2{
         
            self.bindAvatar(remoteKey: user.avatar)
            
        }else{
            if user.sex == .female{
                self.bindAvatar(remoteKey: PH.femaleDefaultURL)
            }else{
                self.bindAvatar(remoteKey: PH.maleDefaultURL)
            }
        }
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        UIView.zenly_animate(withDelay: 0.25, animations: {
            
            self.styleBtn.x = 10
            
            self.styleBtn.alpha = 1
            
        }) { (f) in
            UIView.zenly_animate(withDelay: 0.25, animations: {
                
                self.content_label.x = 30
                
            }) { (f) in
                
            }
        }
        
        UIView.zenly_animate(withDelay: 0.55, animations: {
            
            self.preview_box.alpha = 1
            
        }) { (f) in
            
        }
        
        UIView.zenly_animate(withDelay: 0.75, animations: {
            
            self.left_label.alpha = 1
            self.left_image_view.alpha = 1
            self.left_mistake_image_view.alpha = 1
            
            self.right_image_view.alpha = 1
            self.right_label.alpha = 1
            self.right_mistake_image_view.alpha = 1
            
            self.center_image_view.alpha = 1
            self.center_label.alpha = 1
            self.center_mistake_image_view.alpha = 1
            
        }) { (f) in
            
            UIView.zenly_animate(withDelay: 0, animations: {
                
                self.next_btn.alpha = 1
                
            }) { (f) in
                
                
            }
            
        }
        
        
        
        
        
    }
    
    //    MARK: - Properties
    
    
    lazy var styleBtn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("上传一张照片作为头像")
        control.setTitleColor(UIColor.init(hexString: "#333333")!, for: UIControl.State.normal)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.semibold)
        control.setImageForAllStates(ST_ImageUtils.imageName("注册_icon_emoji头像-1")!)
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 0)
        //        control.backgroundColor = Color.random
        return control
    }()
    
   
    
    
    lazy var content_label:UILabel = {
        
        let control = UILabel.init()
        
        let str = "真实好看的照片能够大幅提高配对率！"
        
        var parag = NSMutableParagraphStyle()
        
        parag.lineSpacing = 5
        
        let attributeStr = str.withAttributes([Attribute.textColor(Color.init(hexString: "#666666")!),Attribute.font(UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)),Attribute.paragraphStyle(parag)])
        
        control.numberOfLines = 0
        
        control.attributedText = attributeStr
        
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        
        return control
    }()
    
    
    
    lazy var preview_box:PreviewRoundShadowView = {
        let control = PreviewRoundShadowView()
        return control
    }()
    
    
    fileprivate lazy var preview_right_bottom_view:UIImageView = {
        let control = UIImageView()
        control.image = ST_ImageUtils.imageName("注册_bot_上传头像")
        return control
    }()
    
    fileprivate lazy var preview_center_view:UIImageView = {
        let control = UIImageView()
        control.image = ST_ImageUtils.imageName("注册_icon_拍照")
        return control
    }()
    
    
    fileprivate lazy var preview_picutre_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = previewBoxWidth/2.0
        control.isHidden = true
        return control
    }()
    
    
    
    
    lazy var preview_box_border_width = 4.cgFloat
    
    lazy var preview_layer_content_view:UIView = {
        let control = UIView()
        control.clipsToBounds = true
        return control
    }()
    
    lazy var preview_icon_view:UIImageView = {
        let control = UIImageView()
        
        control.image = ST_ImageUtils.imageName("注册_img_上传图片电影")
        return control
    }()
    
    lazy var media_picker_click_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.addTarget(self, action: #selector(selectedAction), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    lazy var preview_btn_view:UIImageView = {
        let control = UIImageView()
        //        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.image = ST_ImageUtils.imageName("注册_icon_头像上传")
        return control
    }()
    
    
    
    
    
    lazy var center_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.image = ST_ImageUtils.imageName("注册_img_非人物")
        control.alpha = 0
        return control
    }()
    
    lazy var center_mistake_image_view:UIImageView = {
       let control = UIImageView()
        control.image = ST_ImageUtils.imageName("注册_icon_错误示范")
        control.alpha = 0
        return control
    }()
    
    lazy var left_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.image = ST_ImageUtils.imageName("注册_img_模糊不清")
        control.alpha = 0
        return control
    }()
    
    lazy var left_mistake_image_view:UIImageView = {
       let control = UIImageView()
        control.image = ST_ImageUtils.imageName("注册_icon_错误示范")
        control.alpha = 0
        return control
    }()
    
    lazy var right_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.image = ST_ImageUtils.imageName("注册_img_多人合照")
        control.alpha = 0
        return control
    }()
    
    lazy var right_mistake_image_view:UIImageView = {
       let control = UIImageView()
        control.image = ST_ImageUtils.imageName("注册_icon_错误示范")
        control.alpha = 0
        return control
    }()
    
    lazy var center_label:UILabel = {
        let control = UILabel()
        control.text = "非人物照片"
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        control.textColor = Color.init(hex: 0x333333)
        control.alpha = 0
        return control
    }()
    
    lazy var left_label:UILabel = {
        let control = UILabel()
        control.text = "模糊不清"
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        control.textColor = Color.init(hex: 0x333333)
        control.alpha = 0
        return control
    }()
    
    
    lazy var right_label:UILabel = {
        let control = UILabel()
        control.text = "多人合拍"
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        control.textColor = Color.init(hex: 0x333333)
        control.alpha = 0
        return control
    }()
    
    
    
    lazy var next_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImageForAllStates(ST_ImageUtils.imageName("register_bot_下一步")!)
        
        control.setImage(ST_ImageUtils.imageName("register_bot_下一步diss"), for: UIControl.State.disabled)
        
        control.addTarget(self, action: #selector(next_action), for: UIControl.Event.touchUpInside)
        
        control.isEnabled = false
        
        control.alpha = 0
        
        return control
    }()
    
   
    
    
//    lazy var faceScoreController = FaceScoreViewController()
    
    var avatarKey = ""
//    MARK:- upload Properties
    
//    1,视频 2，图片
    var mediaType:Int?
    
    var mediaSize = CGSize.zero
    
    var selectedImage:UIImage?
    
    var selectedAsset:AVURLAsset?
    
    var thumbnailImage:UIImage?
    
    fileprivate var avatarCloudKey:String?
    
    
//    MARK:- Play Properties
    
    fileprivate lazy var avPlayerView:ST_PairsAVPlayerView = {
       let control = ST_PairsAVPlayerView()
        control.cornerRadius = previewBoxWidth/2.0
        control.isHidden = true
        return control
    }()
    
    
    fileprivate var player:AVPlayer?
    
//    MARK:- Play Method
    /**上传视频完成 预览*/
    @objc func previewVideo(asset:AVURLAsset){
        
        
        self.preview_picutre_view.isHidden = true
        self.preview_right_bottom_view.isHidden = true
        
        self.player?.pause()
        self.player = nil
        
        let item = AVPlayerItem.init(asset: asset)
        let player = AVPlayer.init(playerItem: item)
        self.player = player
        
        guard let castedLayer = avPlayerView.layer as? AVPlayerLayer else{
            return
        }
        
        avPlayerView.isHidden = false
        
        castedLayer.player = self.player
        castedLayer.videoGravity = .resizeAspectFill
        
        player.isMuted = true
        player.play()
        
        self.player = player
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.player_did_finish_playing(note:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)
        
        self.next_btn.isEnabled = true
        
        
    }
    
    
    
    @objc func player_did_finish_playing(note: Notification) {
        
        //        print("播放完成")
        
        if let playerItem = note.object as? AVPlayerItem{
            
            if let currentItem = self.player?.currentItem,playerItem == currentItem{
                
                //                print("DTPlayerViewController -- 两个Player 相同")
                
                if let player = self.player{
                    player.seek(to: CMTime.zero)
                    player.play()
                }
                
                return
            }
        }
        
        
    }
}

extension ST_RegisterAvatarController:TZImagePickerControllerDelegate{
    
    func tz_imagePickerControllerDidCancel(_ picker: TZImagePickerController!) {
        
        self.media_picker_click_btn.isSelected = false
    }
    
    fileprivate func bindAvatar(remoteKey:String){
        
        self.avatarCloudKey = remoteKey
        
        self.preview_picutre_view.pin_setImage(from: remoteKey.url)
        
        self.preview_picutre_view.isHidden = false
        
        self.preview_right_bottom_view.isHidden = true
        
        self.player?.pause()
        self.avPlayerView.isHidden = true
        self.player = nil
        
        self.next_btn.isEnabled = true
        
        self.mediaType = 2
        
        self.selectedImage = nil
        
        self.mediaSize = CGSize.init(width: 100, height: 100)
        
    }
    
    fileprivate func bindAvatar(image:UIImage){
        
        self.avatarCloudKey = nil
        
        self.preview_picutre_view.image = image
        
        self.preview_picutre_view.isHidden = false
        
        self.preview_right_bottom_view.isHidden = true
        
        self.player?.pause()
        self.avPlayerView.isHidden = true
        self.player = nil
        
        self.next_btn.isEnabled = true
        
        self.mediaType = 2
        
        self.selectedImage = image
        
        self.mediaSize = image.size
    }
    
    @objc func selectedAction(){
        
        if media_picker_click_btn.isSelected{
           return
        }
        
        media_picker_click_btn.isSelected = true

        guard let vc = TZImagePickerController.init(maxImagesCount: 1, delegate: self) else{ return }
        vc.allowPickingVideo = false
        vc.didFinishPickingPhotosHandle = {[weak self] photos,assets,isSelectOriginalPhoto in
            
            self?.media_picker_click_btn.isSelected = false
            
            if let image = photos?.first{
                
                self?.bindAvatar(image: image)
                
            }
        }
        
        
         /*
        vc.didFinishPickingVideoHandle = {[weak self] image , assets in
            
            self?.media_picker_click_btn.isSelected = false
            
            guard let ast = assets , let thumbnail = image else { return  }
            
            let options: PHVideoRequestOptions = PHVideoRequestOptions()
                       options.version = .original
            
           PHImageManager.default().requestAVAsset(forVideo: ast, options: options, resultHandler: { (asset, audioMix, info) in
            main_thread_execute {
                
                if let urlAsset = asset as? AVURLAsset{
                 
                    self?.previewVideo(asset: urlAsset)
                    
                    self?.selectedAsset = urlAsset
                    
                    self?.thumbnailImage = thumbnail

                    self?.mediaType = 1
                    
                    self?.mediaSize = thumbnail.size
                }
            }
               
           })
        }
        
        */
        GlobalPresent(toController: vc, animated: true)
    }
    
    
    @objc func next_action(){
        
        
//        guard let type = mediaType else { return  }
        
        self.show_indeterminate_h_u_d()
        
        if let key = self.avatarCloudKey{
            
            let p = ["avatar":key]
            
            self.push_to_remote(param: p)
            
        }else{
            self.uploadImage()
        }
        
        
    }
    
    
    
}

//MARK:- Upload  Push Remote
extension ST_RegisterAvatarController {
    
    
    fileprivate func uploadImage(){
        
        guard let img = selectedImage,let dt = img.pngData() else { return }
        
        
        if img.size.width/img.size.height > 5 || img.size.height/img.size.width > 5{
            
            self.toast(text: "图片尺寸不合适，请重新选择")
            
            return
        }
        
        let content_key = UUID().uuidString
        
        JVUpload(fileKey: content_key, data: dt, uploadProgress: { (f) in
            
        }, success: { (json) in
            
            let p = ["avatar":content_key]
            
            self.push_to_remote(param: p)
            
        }) { (code, err) in
            
            print("上传图片失败 ")
            
            ToastHud(text: err, view: self.view)
        }
        
        
    }
    
    
    
    
    fileprivate func push_to_remote(param:[String:Any]){
        
        
        var p = param
        p.updateValue(mediaSize.width, forKey: "width")
        p.updateValue(mediaSize.height, forKey: "height")
        
        JVrequest(PH.registerAvatarApi254,parameters:p, success: { (json) in
            
            self.hidden_indeterminate_h_u_d()
            
            //TianRegisterStepManager.shared.pushNextStepAction()

        }) { (code, err) in
            
            if code == 400{
                
                let errorView = ST_ProfileErrorView()
                self.view.addSubview(errorView)
                errorView.snp.makeConstraints { (make) in
                    make.edges.equalToSuperview()
                }
                
                self.hidden_indeterminate_h_u_d()
                
            }else{
                ToastHud(text: err, view: self.view)
            }
            
            
        }
        
    }
    
    
    
//    func profileFinishedHanlde(){
//
//        self.navigationController?.pushViewController(ST_SeekPreferenceViewController())
//    }
    
}

//MARK: -
class PreviewRoundShadowView: UIView {
    
    override func layoutSubviews() {
        super.layoutSubviews()

        layer.backgroundColor = UIColor.init(hexString: "#F2F4F7")!.cgColor
        
        
        
//        Borders
        layer.borderColor = UIColor.white.cgColor
        layer.borderWidth = 4
//        Rounded Corners
        layer.cornerRadius = self.bounds.width / 2.0
        
//        Shadows
        
        layer.shadowColor = UIColor.init(hexString: "#E4E9ED")!.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 0)
        layer.shadowRadius = 15
        layer.shadowOpacity = 1
        layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: layer.cornerRadius).cgPath
        
    }
}
